const axios = require('axios');
// 用到的类库
const fs = require('fs-extra')  // 文件读写
const Json2csvParser = require('json2csv').Parser;  // 数据格式转换
const iconv = require('iconv-lite');  //  数据编码转换
const path = require('path')

// 单次
const getUrl1 = (m) => {
    axios.get(`http://hz.hjhj-e.com/api/index/calendar/${m}/150929`)
        .then((response) => {
            // console.log(response.data);
            let info = (response.data || {}).data || {}
            let keys = Object.keys(info)
                .map(item => item.replace(/s/, '')).sort((a, b) => Number(a) - Number(b)).map(item => 's' + item)
            let list = keys.map(key => {
                let item = info[key]
                // item.day = key
                return item
            })
            let headers = Object.keys(info['s1'])
            exportCsv(headers, list)
        })
        .catch((error) => {
            console.error(error);
        });
}


const exportCsv = (headers, list) => {

    // 接口数据转换
    const json2csvParser = new Json2csvParser({ fields: headers });
    const csv = json2csvParser.parse(list);
    console.log(csv);

    // 数据编码调整
    const csvBuf = new Buffer(csv);
    const str = iconv.decode(csvBuf, 'utf-8');
    const str2 = iconv.encode(str, 'gbk');

    // 文件导出
    const file = `\\records\\${Date.now()}.csv`;
    const filePath = path.resolve('./') + file
    fs.outputFileSync(filePath, str2);
}



const getUrl = (year) => {
    let m = Array.from(Array(12)).map((item, key) => `${key < 9 ? '0' : ''}${(key + 1)}`).map(item => {
        return axios.get(`http://hz.hjhj-e.com/api/index/calendar/${year}-${item}/150929`)
    })
    Promise.all(m).then(res => {
        let listAll = [], headers = []

        res.map((_, _m) => {
            let info = (_.data || {}).data || {}
            console.log(Object.keys(info), 'Object.keys(info)');
            let keys = Object.keys(info).map(item => Number(item.replace(/s/, ''))).filter(item => item <= 31).sort((a, b) => a - b).map(item => 's' + item)
            let list = keys.map(key => {
                let item = info[key]
                item.day = key + '__' + (_m + 1) + '月'
                return item
            })

            if (!headers.length) headers = Object.keys(info['s1'])

            listAll = listAll.concat(list)
        })

        exportCsv(headers, listAll)

    }).catch(err => { })
}


// getUrl(2022)
// 单月
getUrl1('2022-10')